package com.example.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

public class LockUtil {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    private ThreadLocal<String> threadLocal = new ThreadLocal<>();

    /*public boolean lock(String key) {
        //可重入锁
        String originValue = threadLocal.get();
        if(originValue!=null ) {
            锁的计数+1
            return true;
        }
        //新锁
        String id = UUID.randomUUID().toString();
        threadLocal.set(id);
        boolean lock = stringRedisTemplate.opsForValue().setIfAbsent(key, id,30, TimeUnit.SECONDS);
        //没有获得锁，始终尝试获取锁
        if(!lock) {
            while(true) {
                lock = stringRedisTemplate.opsForValue().setIfAbsent(key, id,30, TimeUnit.SECONDS);
                if(lock) {
                    break;
                }
            }
        }
        if(lock) {
            //对锁异步续期
            new Runnable() {
                @Override
                public void run() {
                    while (true) {
                        try {
                            Thread.sleep(10);
                            stringRedisTemplate.opsForValue().setIfAbsent(key, id, 30, TimeUnit.SECONDS);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            };
        }
        return lock;
    }

    public void unlock(String key) {
        String id = threadLocal.get();
        锁的计数-1
        if(stringRedisTemplate.opsForValue().get(key).equals(id)) {
            if（锁的计数==1）
            stringRedisTemplate.delete(key);
        }
    }*/
}
